package com.feihong.dubbo.model.util.transform;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 字符串和字符串list的相互转换工具类
 *
 * @author zhufeihong
 */
public class StringTransformUtil {

    /**
     * 默认的分隔符
     */
    private final static String SEPARATOR = ",";

    /**
     * 字符串list转字符串，通过英文逗号分隔
     *
     * @param stringList 字符串list
     * @return string
     */
    public static String listToString(List<String> stringList) {
        if (stringList == null || stringList.isEmpty()) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String item : stringList) {
            String temp = SEPARATOR + item.trim();
            stringBuilder.append(temp);
        }
        return stringBuilder.substring(1);
    }

    /**
     * 根据string的list转为string，通过separator分隔
     *
     * @param stringList 字符串list
     * @param separator  分隔符
     * @return string
     */
    public static String listToString(List<String> stringList, String separator) {
        if (stringList == null || stringList.isEmpty()) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String item : stringList) {
            String temp = separator + item;
            stringBuilder.append(temp);
        }
        return stringBuilder.substring(1);
    }

    /**
     * 字符串转list
     *
     * @param string 字符串
     * @return 转换后的list
     */
    public static List<String> stringToList(String string) {
        if (string == null || string.trim().isEmpty()) {
            return null;
        }
        String[] stringArray = string.split(SEPARATOR);
        List<String> stringList = new ArrayList<>();
        Collections.addAll(stringList, stringArray);
        return stringList;
    }

    /**
     * 把字符串分隔为list
     *
     * @param string    字符串
     * @param separator 分隔符
     * @return 字符串list
     */
    public static List<String> stringToList(String string, String separator) {
        if (string == null || string.trim().isEmpty()) {
            return null;
        }
        String[] stringArray = string.split(separator);
        List<String> stringList = new ArrayList<>();
        Collections.addAll(stringList, stringArray);
        return stringList;
    }
}
